/**
 * @author luther.seven@gmail.com
 */

//search feed backend.joost.com/tolbiac/feed/search?q=string

var favoritesXHR;
var favBase = "www.joost.com"; // no 'http://' or trailing '/'
var favFeed = "api/favorites/get/"; // no preceeding '/'

var favMain;
var favResults;
var favTitle;
var date;
var desc;
var favThumb;
var favPath;

var cursorPosition = 1;

var joostStorageUn = "JoostUn";
var joostUserId;

// Takes a definition document and populates the various DCTK controls
function handleFavoritesResult(doc)
{
    // extract information with XPath
	
	favMain = doc.evaluate("//ns1:feed/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;

	favResults = doc.evaluate("count(//ns1:entry)", doc, NSResolver, XPathResult.ANY_TYPE, null).numberValue;
	
	favTitle = new Array()
	for (var i = 1; i <= favResults; i++){
		favTitle[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	date = new Array()
	for (var i = 1; i <= favResults; i++){
		date[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:updated", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	desc = new Array()
	for (var i = 1; i <= favResults; i++){
		desc[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:content", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
	favPath = new Array()
	for (var i = 1; i <= favResults; i++){
		favPath[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:id", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
		}
    
    var dctk = connected.toolkit;
	
	var favTitleEdit = favMain.split(" ");

	favMainTitle = dctk.getElementById("favMainTitle");
	favMainTitle.text = favTitleEdit[0]+" favorite videos";
	
	connected.debug.print(favTitle[1]);
	connected.debug.print(date[1]);
	connected.debug.print(desc[1]);

	createFavItemList()
}

function onFavoritesXHRStateChange()
{
    if (favoritesXHR.readyState == 4)
    {
        if (favoritesXHR.status == 200)
        {
            handleFavoritesResult(favoritesXHR.responseXML);
        }
    }
}

function startFavoritesRequest()
{
    favoritesXHR = new XMLHttpRequest();
    favoritesXHR.onreadystatechange = onFavoritesXHRStateChange;
    favoritesXHR.open("GET", "http://"+favBase+"/"+favFeed+username+"?fmt=atom&count=100", true);
    favoritesXHR.send(null);
}

function favMainButtonHandler(e)
{
    switch(e.buttonId)
    {
       case dcKeyEvent.BUTTON_ID_BACK:
        {
            // navigate back
            onLoadComplete();
        }
        break;

        case dcKeyEvent.BUTTON_ID_MENU:
        {
			showUserPopup();
        }
        break;
		
		case dcKeyEvent.BUTTON_ID_INFO:
        {
			onLoadFriends();
        }
        break;

    }
}

function playMedia()
{
	var dctk = connected.toolkit;
	
	var height = connected.outputHeight;
	var width = connected.outputWidth;
	
	var params = connected.createPageDescriptor();
	params.uri = playUrl;
	params.pageType = dcIConnected.PT_HTML;
	if (width/height >= 16/9) {
		params.viewConstraints.addResolutionConstraint(640, 360); //16:9
	}
	else if (width/height <= 4/3) {
		params.viewConstraints.addResolutionConstraint(480, 360); //4:3
	}
	params.audioCapture = true;
	//params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
	// load the page
	connected.debug.print("Playing: "+playUrl);
	
	connected.debug.print("Height: "+connected.outputHeight);
	connected.debug.print("Width: "+connected.outputWidth);
	
	connected.loadFromPageDescriptor(params);
}

function favSelected()
{
  cursorPosition = itemList.curSel;
  var videoId = favPath[cursorPosition+1].split("/")
  playUrl = "http://www.joost.com/player/bin/joostPlayer.swf?video="+videoId[3]+"&referer=&mode=player";
  playMedia();
}

function createFavItemList(){
	var item;
	var dctk = connected.toolkit;
	for (var i = 1; i <= favResults; i++){
		favThumb = desc[i].split('\"');
		item = itemList.addItem("id-0"+[i]);
    	item.text = favTitle[i];
		item.img.src = favThumb[3];
		item.showText = true;
	}
}

function onLoadFavorites()
{
    var dctk = connected.toolkit;

    dctk.logicalWidth = 640;
    dctk.logicalHeight = 360;
    
    // create root panel
	var root = dctk.createPanelCtrl("root", true);
	root.width = 640;
	root.height = 360;

	root.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	root.backgroundImg.src = "joost-background.jpg";
	root.color.rgb = 0x333333;
	root.filled = true;
	root.onUnhandledKeyEvent = favMainButtonHandler;
	dctk.rootPanel = root;
	
	var logo = dctk.createImageCtrl("logo", true);
	logo.setRect(540, 310, 630, 350);
	logo.img.src = "joost-logo.png";
	root.addChild(logo);
	
	var storageUn = connected.openStorage(joostStorageUn,true);
	username = storageUn.get(joostUserId);
	
	var favMainTitle = dctk.createLabelCtrl("favMainTitle", true);
    favMainTitle.font = dctk.createFontByFacename("DIN-Bold", false, false);
    favMainTitle.setRect(0, 310, 540, 350);
    favMainTitle.textColor.rgb = 0xCCCCCC;
    favMainTitle.fontSize = 20;
    favMainTitle.align = dctkLabel.TS_CENTER;
	favMainTitle.valign = dctkLabel.TS_MIDDLE;
    favMainTitle.text = "Loading...";
    root.addChild(favMainTitle);
	
	var menuTxt = dctk.createLabelCtrl("menuTxt", true);
    menuTxt.font = dctk.createFontByFacename("DIN-Bold", false, false);
    menuTxt.setRect(0, 8, 640, 28);
    menuTxt.textColor.rgb = 0xcccccc;
    menuTxt.fontSize = root.height/22;
    menuTxt.align = dctkLabel.TS_CENTER;
	menuTxt.valign = dctkLabel.TS_MIDDLE;
	menuTxt.text = "(press MENU to change login / press INFO for friends)";
    root.addChild(menuTxt);
	
	itemList = dctk.createThumbCtrl("itemList", true);
    itemList.setRect(20, 30, 610, 310);
	itemList.thumbHCount = 4;
    itemList.thumbVCount = 2;
	itemList.fontSize = 14;
	//itemList.favThumbHGap = 0.08;
	itemList.spacing = 0;
	itemList.marquee = true;
    itemList.keyWrap = true;
	itemList.showPageIndicator = true;
	itemList.textColor.rgb = 0xcccccc;
	itemList.textSelColor.rgb = 0x000000;
	itemList.labelColor.rgb = 0x000000;
	itemList.labelSelColor.rgb = 0xCCCCCC;
	itemList.onSelect = favSelected;
	root.addChild(itemList);
	
	if (username == "") {
		showUserPopup();
	}
	else if (username == null) {
		showUserPopup();
	}
	
	startFavoritesRequest();
	
	//dctk.screenFade(1, 0, 0.5);
	
	//connected.toolkit.debug.drawElementOutline = true;
}

